package com.code4j.ai.mcp.client.stdio;

import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.client.transport.ServerParameters;
import io.modelcontextprotocol.client.transport.StdioClientTransport;
import org.springframework.ai.mcp.SyncMcpToolCallbackProvider;
import org.springframework.ai.mcp.client.autoconfigure.NamedClientMcpTransport;
import org.springframework.ai.mcp.client.autoconfigure.properties.McpStdioClientProperties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class AiService implements BeanFactoryAware {

    List<NamedClientMcpTransport> stdioTransports;
    ServerParameters serverParameters ;
    List<McpSyncClient> mcpSyncClients;
    DefaultListableBeanFactory beanFactory;

    public AiService(
            List<NamedClientMcpTransport> stdioTransports,
            McpStdioClientProperties stdioProperties,
            List<McpSyncClient> mcpSyncClients

    ) {
        this.serverParameters=stdioProperties.toServerParameters().get("mcp-server-weather");
        this.mcpSyncClients=mcpSyncClients;
        this.stdioTransports=stdioTransports;
    }

    public void changeMcp(String username) throws InterruptedException {
        // 把之前的stdio移除掉
        NamedClientMcpTransport transport = stdioTransports
                .stream()
                .filter(namedClientMcpTransport -> namedClientMcpTransport.name().equals("mcp-server-weather"))
                .findFirst().get();
        stdioTransports.remove(transport);

        transport.transport().closeGracefully().block();


        // 修改环境变量username
        ServerParameters serverParameters=ServerParameters.builder("java")
                        .args("-Dspring.ai.mcp.server.stdio=true",
                                "-Dlogging.pattern.console=",
                                "-jar",
                                "D:\\ideaworkspace\\git_pull\\mcp-all\\mcp-stdio-server\\target\\mcp-stdio-server-xs-1.0.jar"
                        ).addEnvVar("username", username).build();
        var transportnew = new StdioClientTransport(serverParameters);

        // 加入新的stdio
        stdioTransports.add(new NamedClientMcpTransport("mcp-server-weather"+username, transportnew));



        // 销毁掉相关bean 重新加载bean 相当于会建立stdio mcp server 连接）
        beanFactory.destroySingleton("mcpToolCallbacks");
        beanFactory.destroySingleton("mcpSyncClients");
        beanFactory.destroySingleton("toolCallbacks");
    }


    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory=((DefaultListableBeanFactory )beanFactory);
    }


}
